package com.up.cloudfeiyibackend.interceptor;

import com.up.cloudfeiyibackend.constant.HttpStatusConstant;
import com.up.cloudfeiyibackend.properties.JwtProperties;
import com.up.cloudfeiyibackend.util.JwtUtil;
import com.up.cloudfeiyibackend.util.UserHolder;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.ExpiredJwtException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

/**
 * JWT拦截器
 */
@Slf4j
@Component
@RequiredArgsConstructor
public class JwtInterceptor implements HandlerInterceptor {

    private final JwtProperties jwtProperties;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // 放行非控制器方法请求
        if (!(handler instanceof HandlerMethod)) {
            return true;
        }

        // 获取请求头中的Token
        String token = request.getHeader(jwtProperties.getTokenName());
        log.info("请求拦截，Token: {}", token);

        if (token == null) {
            log.info("用户未登录授权");
            response.setStatus(HttpStatusConstant.UNAUTHORIZED); // 响应未授权
            return false;
        }

        // 解析Token
        try {
            log.info("开始验证Token");
            Claims claims = JwtUtil.parseJwt(jwtProperties.getSecretKey(), token);
            Object userId = claims.get("userId");
            log.info("当前用户ID: {}", userId);
            UserHolder.set(((Number) userId).longValue());
            return true;
        } catch (ExpiredJwtException  jwte){
            log.info("Token已过期");
            response.setStatus(HttpStatusConstant.FORBIDDEN); // 响应Token已过期
            return false;
        } catch (Exception e) {
            log.info("Token验证失败");
            response.setStatus(HttpStatusConstant.UNAUTHORIZED); // 响应Token验证失败
            return false;
        }
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        // 清理ThreadLocal上下文
        UserHolder.remove();
    }
}
